package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.Organization;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.OrganizationServiceInterface;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * 组织管理控制器，处理组织相关的HTTP请求。
 * 支持对组织信息的增删改查操作，API路径为/organizations。
 * @author 作者名
 * @version 1.0
 */
@WebServlet("/organizationsA")
public class OrganizationController extends HttpServlet {
    // 组织服务接口，用于处理业务逻辑
    private final OrganizationServiceInterface organizationServiceInterface
            = ServiceFactory.getService(OrganizationServiceInterface.class, "OrganizationServiceImpl");

    /**
     * 处理GET请求，获取组织信息。
     * 当提供id参数时，返回对应id的组织详情；否则返回所有组织列表。
     * @param request HTTP请求对象，可携带id查询参数
     * @param response HTTP响应对象，返回JSON格式数据
     * @throws ServletException 如果Servlet处理遇到问题
     * @throws IOException 如果I/O操作失败
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String idParam = request.getParameter("id");
        // 根据是否存在id参数判断是单个查询还是列表查询
        if (idParam != null) {
            try {
                Long id = Long.parseLong(idParam);
                Organization organization = organizationServiceInterface.findById(id);
                if (organization != null) {
                    String json = JSON.toJSONString(organization);
                    out.println(json);
                } else {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    JSONObject error = new JSONObject();
                    error.put("message", "组织不存在");
                    out.println(error.toJSONString());
                }
            } catch (NumberFormatException e) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                JSONObject error = new JSONObject();
                error.put("message", "ID格式错误");
                out.println(error.toJSONString());
            }
        } else {
            Collection<Organization> organizations = organizationServiceInterface.findAll();
            String json = JSON.toJSONString(organizations);
            out.println(json);
        }
    }

    /**
     * 处理POST请求，创建新的组织。
     * 需要提供name、no、remarks和可选的parentId参数。
     * @param request HTTP请求对象，包含JSON格式的请求体
     * @param response HTTP响应对象，返回操作结果
     * @throws ServletException 如果Servlet处理遇到问题
     * @throws IOException 如果I/O操作失败
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        // 读取请求体中的JSON数据
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(sb.toString());
        String name = jsonObject.getString("name");
        String no = jsonObject.getString("no");
        String remarks = jsonObject.getString("remarks");
        Long parentId = jsonObject.getLong("parentId");
        Organization parent = null;
        // 验证父组织是否存在
        if (parentId != null) {
            parent = organizationServiceInterface.findById(parentId);
            if (parent == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                JSONObject error = new JSONObject();
                error.put("message", "上级组织不存在");
                out.println(error.toJSONString());
                return;
            }
        }
        // 创建并保存新组织
        Organization organization = new Organization();
        organization.setName(name);
        organization.setNo(no);
        organization.setRemarks(remarks);
        organization.setParent(parent);
        organizationServiceInterface.save(organization);
        response.setStatus(HttpServletResponse.SC_CREATED);
        JSONObject success = new JSONObject();
        success.put("message", "组织创建成功");
        out.println(success.toJSONString());
    }

    /**
     * 处理PUT请求，更新已有组织信息。
     * 需要提供id、name、no、remarks和可选的parentId参数。
     * @param request HTTP请求对象，包含JSON格式的请求体
     * @param response HTTP响应对象，返回操作结果
     * @throws ServletException 如果Servlet处理遇到问题
     * @throws IOException 如果I/O操作失败
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        // 读取请求体中的JSON数据
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(sb.toString());
        Long id = jsonObject.getLong("id");
        // 验证必须参数是否存在
        if (id == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            JSONObject error = new JSONObject();
            error.put("message", "更新操作必须提供ID");
            out.println(error.toJSONString());
            return;
        }
        // 检查目标组织是否存在
        Organization existingOrganization = organizationServiceInterface.findById(id);
        if (existingOrganization == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            JSONObject error = new JSONObject();
            error.put("message", "组织不存在");
            out.println(error.toJSONString());
            return;
        }
        // 更新组织信息
        String name = jsonObject.getString("name");
        String no = jsonObject.getString("no");
        String remarks = jsonObject.getString("remarks");
        Long parentId = jsonObject.getLong("parentId");
        Organization parent = null;
        if (parentId != null) {
            parent = organizationServiceInterface.findById(parentId);
            if (parent == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                JSONObject error = new JSONObject();
                error.put("message", "上级组织不存在");
                out.println(error.toJSONString());
                return;
            }
        }
        existingOrganization.setName(name);
        existingOrganization.setNo(no);
        existingOrganization.setRemarks(remarks);
        existingOrganization.setParent(parent);
        organizationServiceInterface.update(existingOrganization);
        JSONObject success = new JSONObject();
        success.put("message", "组织更新成功");
        out.println(success.toJSONString());
    }

    /**
     * 处理DELETE请求，删除指定组织。
     * 需要提供id查询参数。
     * @param request HTTP请求对象，必须包含id参数
     * @param response HTTP响应对象，返回操作结果
     * @throws ServletException 如果Servlet处理遇到问题
     * @throws IOException 如果I/O操作失败
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String idParam = request.getParameter("id");
        // 验证必须参数
        if (idParam == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            JSONObject error = new JSONObject();
            error.put("message", "删除操作必须提供ID");
            out.println(error.toJSONString());
            return;
        }
        try {
            Long id = Long.parseLong(idParam);
            Organization existingOrganization = organizationServiceInterface.findById(id);
            // 检查目标组织是否存在
            if (existingOrganization == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                JSONObject error = new JSONObject();
                error.put("message", "组织不存在");
                out.println(error.toJSONString());
                return;
            }
            // 执行删除操作
            organizationServiceInterface.delete(id);
            JSONObject success = new JSONObject();
            success.put("message", "组织删除成功");
            out.println(success.toJSONString());
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            JSONObject error = new JSONObject();
            error.put("message", "ID格式错误");
            out.println(error.toJSONString());
        }
    }
}